#!/usr/bin/env python
# coding: utf-8
# author: Wesley

import logging

from django.http import JsonResponse
from django.contrib.auth.models import User
from django.conf import settings

from lib.common import AbstractHandler
from lib.sms import sender
from services.datamodel.share import BusinessCode
from services.datamodel.student.models import mm_Student

app_logger = logging.getLogger('django')


class UserHandler(AbstractHandler):
    def __init__(self):
        AbstractHandler.__init__(self, app_logger)
        self.app_logger = app_logger
        self.METHOD_TAB = {

            'GET': {
                'checkuserexist': self.handle_check_user_exists,
            },
            'POST': {
                'register': self.register_by_share_link,
            }
        }

    # @ratelimit(key='get:username',rate='1/m')
    def handle_check_user_exists(self, request):
        """
        :param request:
        :return:

        Request sample:
            curl --cookie "sessionid=o1qokt6go8r9jyhahk7lexg4482w7b3f"
            "http://127.0.0.1:8000/api/general/user/?action=checkuserexist&username=weizhengbin"
        """
        self.checkMandatoryParams(request, ['username'])

        if getattr(request, 'limited', False):
            return JsonResponse({'retcode': settings.RATELIMITTED_CODE, 'msg': '操作频繁, 请稍后再试'})
        if User.objects.filter(username=request.param_dict['username']).exists():
            exist = 1
        else:
            exist = 0

        return JsonResponse({'retcode': 0, 'exist': exist})

    def register_by_share_link(self, request):

        self.checkMandatoryParams(request, ['phonenumber', 'smscode'])
        self.is_not_zero_int_params(request, 'uid')
        phonenumber = request.param_dict['phonenumber'].strip()
        smscode = request.param_dict['smscode']
        # check smscode
        sms_ret = sender.checkcode(BusinessCode.WREGISTER, phonenumber, smscode)
        if sms_ret['retcode']:
            return JsonResponse(sms_ret)
        uid = request.param_dict.get('uid') if request.param_dict.get('uid') else None
        one = request.param_dict.get('one') if request.param_dict.get('one') else None
        two = request.param_dict.get('two') if request.param_dict.get('two') else None
        username = settings.USERNAME_TYPE_PREFIX.STUDENT + phonenumber

        mweb = 2 if request.param_dict.get('mweb') else 1

        if not User.objects.filter(username=username).exists():
            ret = mm_Student.addStudent(username, phonenumber, phonenumber=phonenumber, inviterid=uid,
                                        register_from=mweb, one=one, two=two)
            # 注册送优惠券取消
            # if ret['retcode'] == 0:
            #     send_coupon_after_student_register(ret['user_id'])
        else:
            ret = {
                'retcode': 1,
                'msg': '手机号已注册'
            }
        return JsonResponse(ret)


handler = UserHandler()
